package com.elab.config.customize;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.fasterxml.jackson.databind.ObjectMapper;

public class AuthExceptionEntryPoint implements AuthenticationEntryPoint{
	protected Logger logger = LogManager.getLogger(getClass());
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ae)
			throws IOException, ServletException {
		Map<String, Object> map = new HashMap<String, Object> ();
		map.put("error", "401");
		map.put("message", ae.getMessage());
		map.put("path", request.getServletPath());
		map.put("timestamp", String.valueOf(new Date().getTime()));
		response.setContentType("application/json");
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		//response.sendRedirect(request.getServletPath());
		try {
			logger.info("进入 Entry方法："+ae.getMessage());
			/**
			 * 数据返回
			ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(response.getOutputStream(), map);
			 * */

			response.sendRedirect("/login");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
